<?php

/**
 * 显示错误信息
 */
error_reporting(E_ALL);

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

/**
 * 应用 URL 地址
 */
define('URL', 'http://test.1999.me');

/**
 * 数据库配置信息
 */
define('DB_HOST', '123.57.147.131');
define('DB_USER', 'root');
define('DB_PASS', 'qx_123456');
define('DB_NAME', 'preparation');

/**
 * 公众号配置信息
 */
define('APPID', 'wx44d991f12db4d711');
define('APPSECRET', '6812cf5b44f130ed5e5fd8cb96ad0623');

/**
 * 用户 AccessToken 有效期
 */
define('EXPIRES_SECONDS', 7200);

/**
 * 数据库链接
 */
function createDbConnection()
{
    return new PDO(sprintf('mysql:dbname=%s;host=%s;charset=UTF8', DB_NAME, DB_HOST), DB_USER, DB_PASS);
}

/**
 * 根据用户 Openid 获取用户 AccessToken
 */
function getAccessTokenByOpenid($openid)
{
    $db = createDbConnection();

    $stmt = $db->prepare('SELECT a.* FROM t_user u JOIN t_access_token a ON a.user_id = u.id WHERE u.openid = :openid');
    $stmt->bindParam(':openid', $openid, PDO::PARAM_STR);
    $stmt->execute();

    $accessToken = $stmt->fetch(PDO::FETCH_ASSOC);

    if (false !== $accessToken) {

        $expireAt = (time() + EXPIRES_SECONDS);

        $stmt = $db->prepare('UPDATE t_access_token SET expires_dt = :expires_dt WHERE id = :id');
        $stmt->bindParam(':expires_dt', $expireAt, PDO::PARAM_INT);
        $stmt->bindParam(':id', $accessToken['id'], PDO::PARAM_INT);
        $stmt->execute();
    }

    return $accessToken;
}

/**
 * 根据用户 AccessToken 获取用户信息
 */
function getUserByAccessToken($accessToken)
{
    $db = createDbConnection();

    $stmt = $db->prepare('SELECT u.* FROM t_user u JOIN t_access_token a ON a.user_id = u.id WHERE a.token = :token');
    $stmt->bindParam(':token', $accessToken, PDO::PARAM_STR);
    $stmt->execute();

    return $stmt->fetch(PDO::FETCH_ASSOC);
}

/**
 * 为指定用户设置 Openid
 */
function setOpenidByUesrid($userid, $openid)
{
    $db = createDbConnection();

    $stmt = $db->prepare('UPDATE t_user SET openid = :openid WHERE id = :id');
    $stmt->bindParam(':openid', $openid, PDO::PARAM_STR);
    $stmt->bindParam(':id',     $userid, PDO::PARAM_INT);
    $stmt->execute();

    return $stmt->rowCount();
}

/**
 * 自动入加入口
 */
require '../vendor/autoload.php';
